/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.view.finance;

import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.primefaces.context.RequestContext;
import src.domain.finance.Bv;
import src.domain.finance.Bvdet;
import src.domain.security.Users;
import src.domain.system.Numbering;
import src.services.CRUEDService;
import src.services.finance.BankModel;
import src.services.finance.BvModel;
import src.services.finance.BvaccntModel;
import src.services.finance.BvtypeModel;
import src.services.gl.CurrencyModel;
import src.services.system.BranchModel;
import src.util.Messager;
import src.view.security.LoginBean;

/**
 *
 * @author jay
 */
@ManagedBean
@SessionScoped
public class BvBean implements Serializable {

    private List<SelectItem> availableBank, availableCurrency, availableBvaccnt, availableType;
    private Bv bv;
    private Bvdet unsaveDetail;
    private Users users;      
    private BankModel bankHelper; 
    private CurrencyModel currencyHelper; 
    private BvaccntModel bvaccntHelper; 
    private BvtypeModel typeHelper; 
    private CRUEDService csHelper;
    private BvModel helper;
    private Integer branchId, bvaccntId, idx;
        
    private boolean editMode = false, editDetailMode=true, insertionMode=false;
    
    public BvBean() {
        ambilUser();
        bankHelper = new BankModel();
        currencyHelper = new CurrencyModel();
        bvaccntHelper = new BvaccntModel();
        typeHelper = new BvtypeModel();
        csHelper = new CRUEDService();
        helper = new BvModel();
        newData();
        editMode=false;
    }
    
    private boolean cekConfig() {
        boolean complete=true;
        this.branchId = users.getBranch().getBranchId();
        if (this.branchId==null) complete=false;
        if(complete==false) Messager.showWarning("loanUnconfig");
        return complete;
    }
    
    public boolean isEditMode() {
        return editMode;
    }
    
    public Bv getBv() {
        return bv;
    }

    public Integer getBvaccntId() {
        return bvaccntId;
    }

    public void setBvaccntId(Integer bvaccntId) {
        this.bvaccntId = bvaccntId;
    }
    
    public void setBv(Bv bv) {
        this.bv = bv;
    }

    public List<SelectItem> getAvailableBank() {
        return availableBank;
    }

    public List<SelectItem> getAvailableCurrency() {
        return availableCurrency;
    }
    
    public List<SelectItem> getAvailableBvaccnt() {
        return availableBvaccnt;
    }

    public List<SelectItem> getAvailableType() {
        return availableType;
    }

    public Bvdet getUnsaveDetail() {
        return unsaveDetail;
    }

    public void setUnsaveDetail(Bvdet unsaveDetail) {
        this.unsaveDetail = unsaveDetail;
    }
        
     private String newNumber() {
        String no = null;
        
        if (bv.getBranchId() != null) {
            Numbering currentNo = csHelper.getNextTrxNumber(7, bv.getBranchId(), 0, 1);
            no = currentNo.getTrxNum();
        }
        return no;
    }
     
    private void initForm() {
        this.availableCurrency =  currencyHelper.listAll();
        this.availableBank = bankHelper.listAll();
        this.availableBvaccnt = bvaccntHelper.listAll();
        this.availableType = typeHelper.listAll();
        this.editMode = true;
    }
    
    public final void newData() { 
        initForm();
        cekConfig();
        if (this.bv!=null) bv = null;
        this.bv = new Bv();
        this.bv.getBvdets().add(new Bvdet());
        this.bv.setBranchId(branchId);
        
        insertionMode = true;
    }
    
    public void openData() {
        initForm();
        insertionMode = false;
    }
        
    /*
    public Customer getCustomerByCIF(String cif) {
        CustomerModel helper = new CustomerModel();
        Customer cust = helper.getByCif(cif);
        return cust;
    }
    
    public void getBvCustomer() {
        String cif = bv.getCustomer().getCif();
        
        if (cif!=null ) {
            Customer customer = getCustomerByCIF(cif);
            if (customer==null) {
                //reset
                this.bv.setCustomer(new Customer());
                Messager.showWarning("customerNotFound");
            }
            
            else this.bv.setCustomer(customer);
        }
    }
    
    * 
    */
    public String getBvaccntName(Integer bvaccntId) {
        String nama = "";
        
        if (bvaccntId!=null) {
            int i=0;
            boolean found=false;
            while (i<availableBvaccnt.size() && !found) {
                SelectItem it = availableBvaccnt.get(i);
                found = bvaccntId.equals(it.getValue()) ? true:false;
                if (found) nama = it.getLabel();
                i++;
            }
        }
        return nama;
    }
    
    private void removeEmptyRow(){
        for(int i = 0; i<bv.getBvdets().size(); i++){
           Integer id = bv.getBvdets().get(i).getBvaccntId();
           
           if(id==null) {
               bv.getBvdets().remove(i);
               i--;
           }
        }
    }
    
    public void handleRemoveDetail() {  
        if (bv.getBvdets().size() == 1) bv.getBvdets().add(new Bvdet());
    }  
    
    public void newDetail() {
        this.unsaveDetail = new Bvdet();
        editDetailMode = false;
    }
    
    public void editDetail(Bvdet data) {
        bvaccntId = data.getBvaccntId();
        idx = bv.getBvdets().indexOf(data);
        this.unsaveDetail = Bvdet.clone(data);
        editDetailMode = true;
    }
    
    public void saveDetail() {
        boolean success=true;
        try {
            
            unsaveDetail.setBvaccntId(bvaccntId);
            if(!editDetailMode) {
                this.bv.getBvdets().add(unsaveDetail);
                removeEmptyRow();
                
            } else this.bv.getBvdets().set(idx, Bvdet.clone(unsaveDetail));


        } catch (RuntimeException e) {success=false;
        } finally {Messager.showSaveUpdateStatus(success);}
    }
    
    public void trySave() {
        if (cekConfig()==true) save();
    }
    
    private void save() {
        removeEmptyRow();
        bv.setBvNo(newNumber());
        bv.setBvdets(bv.getBvdets());
                
        boolean success = helper.saveData(bv);
        
        // re-insert
        if (!success && insertionMode) bv.setBvId(null);
        else insertionMode = false;
        
        editMode = !success;        
        Messager.showSaveUpdateStatus(success);   
        RequestContext.getCurrentInstance().addCallbackParam("success", success); 
    }
    
    public void delete() {
        bv.getBvdets().clear();
        bv.setBvdets(bv.getBvdets());
        
        boolean success = helper.deleteData(bv);
        editMode = !success;
        if (success) {
            bv = new Bv();
            bv.getBvdets().add(new Bvdet());
        }
                
        Messager.showDeleteStatus(success);     
    }
    
    private void ambilUser() {
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean logBean = (LoginBean) context.getApplication().evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);
        this.users = logBean.getSelectedUser();
    }
        
    
}
